package com.sky.chapter1.waitAndnotify;

/**
 * description: 举例说明notify和notifyAll方法的具体含义以及一些需要注意的地方
 *
 * @author : 陈庆彪
 * date :  2020-06-26 20:09
 **/
public class notifyAndNotifyAll {
    //创建资源
    private static volatile Object resourceA = new Object();


    public static void main(String[] args) throws InterruptedException {
        //创建线程
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                //获取resourceA共享资源的监视器锁
                synchronized (resourceA) {
                    System.out.println("threadA get resourceA lock");
                    try {
                        System.out.println("threadA begin wait");
                        resourceA.wait();  //停止线程并释放资源
                        System.out.println("threadA end wait");
                    } catch (InterruptedException E) {
                        E.printStackTrace();
                    }
                }
            }
        }, "线程A");

        //创建线程
        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {
                //获取resourceA共享资源的监视器锁
                synchronized (resourceA) {
                    System.out.println("threadB get resourceA lock");
                    try {
                        System.out.println("threadB begin wait");
                        resourceA.wait(); //停止线程并释放资源
                        System.out.println("threadB end wait");
                    } catch (InterruptedException E) {
                        E.printStackTrace();
                    }
                }
            }
        },  "线程B");
        //创建线程
        Thread threadC = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (resourceA) {
                    System.out.println("threadC begin notify");
//                    resourceA.notify();
                    resourceA.notifyAll();
                }
            }
        });

        //启动线程
        threadA.start();
        threadB.start();


        Thread.sleep(1000);

        threadC.start();


        threadA.join();
        threadB.join();
        threadC.join();

        System.out.println("main over");

    }
}
